package com.bwie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bwie.utils.R;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.UserMapper;
import com.bwie.domain.User;
import com.bwie.service.UserService;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public R myLogin(User user) {
        int i = 5;
        //查询用户账号是否存在
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, user.getUsername());
        User one = userMapper.selectOne(wrapper);
        //用户不存在
        if (one == null) {
            return R.ERROR(404, "用户名称不存在");
        }
        //密码错误
        if (!one.getPassword().equals(user.getPassword())) {
            i=i-1;
            return R.ERROR(404, "密码错误,还有" + i + "次尝试的机会哦");
        }

        //实现jwt系统鉴权
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "bwie").claim("userId", one.getUserId()).compact();
        //放进redis中存30分钟
        redisTemplate.opsForValue().set("token" + one.getUserId(), token, 30, TimeUnit.MINUTES);
        one.setToken(token);
        //返回响应
        return R.OK(one);
    }
}
